package org.lewis.common.interceptors;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lewis.common.Constants;
import org.lewis.common.domain.User;
import org.lewis.common.domain.VCode;
import org.lewis.common.service.UserService;
import org.lewis.common.service.VCodeService;
import com.tocersoft.framework.core.annotations.Component;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.web.Execution;
import com.tocersoft.framework.web.HttpUtils;
import com.tocersoft.framework.web.WebUtils;
import com.tocersoft.framework.web.annotations.InterceptorOrder;
import com.tocersoft.framework.web.interceptors.Interceptor;
import com.tocersoft.framework.web.interceptors.InterceptorChain;

/**
 * 用户登录状态核心拦截器
 */
@Component
@InterceptorOrder(2)
public class LoginInterceptor implements Interceptor {

	Log log = LogFactory.getLog(LoginInterceptor.class);
	
	@Injection("userService")
	private UserService userService;
	
	@Injection
	private VCodeService vcodeService;

	public void intercept(Execution execution, InterceptorChain chain)
			throws Exception {
		User user = (User) WebUtils.getSession().getAttribute(Constants.CURRENTUSER);
		if (user == null) {
			String code = HttpUtils.getCookie(Constants.CLIENTAUTHCOOKIEKEY);
			if (StringUtils.isNotBlank(code)) {
				log.info("Found login cookie:"+code);
				VCode vcode=vcodeService.getByCode(code);
				if(null!=vcode){
					user=userService.getUserById(vcode.getUid());
					if(null!=user&&vcode.getCode().equals(code)&&user.getStatus()!=2){
						log.info("Auto login success，uid:" + user.getId());
						WebUtils.getSession().setAttribute(Constants.CURRENTUSER, user);
					}
				}else{
					HttpUtils.removeCookie(Constants.CLIENTAUTHCOOKIEKEY);
					log.info("Cookie key missed :(");
				}
			}
		}
		chain.doInterceptor(execution);
	}
}
